package com.gewei.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gewei.dao.MemberDao;
import com.gewei.entity.PageResult;
import com.gewei.entity.QueryPageBean;
import com.gewei.pojo.Member;
import com.gewei.service.MemberService;
import com.gewei.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author gewei
 */
@Service(interfaceClass = MemberService.class)
@Transactional
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberDao memberDao;

    /**
     * 根据手机号查询会员
     *
     * @param telephone
     * @return
     */
    public Member findByTelephone(String telephone) {
        return memberDao.findByTelephone(telephone);
    }

    /**
     * 保存会员信息
     *
     * @param member
     */
    public void add(Member member) {
        String password = member.getPassword();
        if (password != null) {
            //  使用 MD5 将明文密码进行加密
            password = MD5Utils.md5(password);
            member.setPassword(password);
        }
        memberDao.add(member);
    }

    /**
     * 根据月份查询会员数量
     *
     * @param months 2018.5
     * @return
     */
    public List<Integer> findMemberCountByMonths(List<String> months) {
        List<Integer> memberCount = new ArrayList<>();
        for (String month : months) {
            //  2018.5.31
            String date = month + ".31";
            Integer count = memberDao.findMemberCountBeforeDate(date);
            memberCount.add(count);
        }
        return memberCount;
    }


    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Member> page = memberDao.selectByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    public void deleteById(Integer id) {
        memberDao.deleteById(id);
    }

    public void edit(Member member) {
        memberDao.edit(member);
    }

    public Member findById(Integer id) {
        return memberDao.findById(id);
    }

    @Override
    public List<Member> findAll() {
        return memberDao.findAll();
    }
}